package cn.surveyking.server.core.security;

import cn.surveyking.server.core.uitls.MapBeanUtils;
import cn.surveyking.server.domain.dto.ThirdUserView;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import io.jsonwebtoken.security.SignatureException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.security.Key;
import java.util.Date;

/**
 * @author huang.cz
 * @date 2023/03/15
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class ThirdJwtTokenUtil {

    @Value("${jwt.security-key}")
    private String jwtSecret;

    public String generateAccessToken(ThirdUserView user) {
        return Jwts.builder()
                .setSubject(user.getLoginName())
                .claim("role", user.getRole())
                .claim("loginName", user.getLoginName())
                .claim("userName", user.getUserName())
                .claim("mobile", user.getMobile())
                .setIssuedAt(new Date())
                .signWith(Keys.hmacShaKeyFor(jwtSecret.getBytes()))
                .compact();
    }

    public boolean validate(String token) {
        try {
            Jwts.parserBuilder().setSigningKey(Keys.hmacShaKeyFor(jwtSecret.getBytes())).build().parseClaimsJws(token);
            return true;
        } catch (SignatureException ex) {
            log.error("Invalid JWT signature - {}", ex.getMessage());
        } catch (MalformedJwtException ex) {
            log.error("Invalid JWT token - {}", ex.getMessage());
        } catch (ExpiredJwtException ex) {
            log.error("Expired JWT token - {}", ex.getMessage());
        } catch (UnsupportedJwtException ex) {
            log.error("Unsupported JWT token - {}", ex.getMessage());
        } catch (IllegalArgumentException ex) {
            log.error("JWT claims string is empty - {}", ex.getMessage());
        }
        return false;
    }

    public ThirdUserView getUser(String token) {
        try {
            return MapBeanUtils.mapToBean(
                    Jwts.parserBuilder()
                            .setSigningKey(Keys.hmacShaKeyFor(jwtSecret.getBytes()))
                            .build()
                            .parseClaimsJws(token)
                            .getBody(),
                    ThirdUserView.class);
        } catch (Exception e) {
            return null;
        }
    }

    public static void main(String[] args) {
        ThirdUserView user = new ThirdUserView();
        user.setUserName("测试");
        user.setLoginName("ceshi");
        user.setRole("普通用户");
        user.setMobile("13400000001");
        System.out.println(new ThirdJwtTokenUtil().generateAccessToken(user));
    }
}
